import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import api from '@/utils/api'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const user = ref(JSON.parse(localStorage.getItem('user') || 'null'))
  const userPermissions = ref(JSON.parse(localStorage.getItem('userPermissions') || '[]'))
  const loading = ref(false)

  // 计算属性
  const isAuthenticated = computed(() => {
    return !!token.value && !!user.value
  })

  // 获取验证码
  const getCaptcha = async () => {
    try {
      const response = await api.get('/api/Auth/captcha')
      return {
        success: true,
        data: response.data
      }
    } catch (error) {
      console.error('获取验证码失败:', error)
      return {
        success: false,
        message: error.response?.data?.message || '获取验证码失败'
      }
    }
  }

  // 登录
  const login = async (credentials) => {
    loading.value = true
    try {
      // 确保字段名首字母大写，匹配后端期望的格式
      const loginData = {
        Username: credentials.username,
        Password: credentials.password,
        Captcha: credentials.captcha
      }
      
      // 如果有sessionId，添加到请求头中
      const headers = {}
      if (credentials.sessionId) {
        headers['X-Session-Id'] = credentials.sessionId
      }
      
      console.log('发送登录请求:', loginData)
      const response = await api.post('/api/Auth/login', loginData, { headers })
      
      // 检查响应状态
      if (response.status === 200 && response.data) {
        const { token: authToken, id, username, fullName, role, userPhone, expiresAt } = response.data
        
        // 保存到状态
        token.value = authToken
        user.value = { id, username, fullName, role, userPhone: userPhone || '', expiresAt }
        
        // 保存到本地存储
        localStorage.setItem('token', authToken)
        localStorage.setItem('user', JSON.stringify(user.value))
        
        // 设置API默认请求头
        api.defaults.headers.common['Authorization'] = `Bearer ${authToken}`
        
        console.log('登录成功，保存的数据:', {
          token: authToken,
          user: user.value,
          isAuthenticated: !!authToken && !!user.value
        })
        
        // 获取用户权限
        try {
          const permissionResult = await getUserPermissions(username)
          if (permissionResult.success) {
            console.log('用户权限获取成功，权限数量:', permissionResult.data.length)
          } else {
            console.warn('用户权限获取失败:', permissionResult.message)
          }
        } catch (permissionError) {
          console.error('获取用户权限时发生错误:', permissionError)
        }
        
        // 触发用户登录状态变化事件
        window.dispatchEvent(new CustomEvent('userLoginStatusChanged'))
        
        return { success: true }
      } else {
        return { success: false, message: response.data?.message || '登录失败' }
      }
    } catch (error) {
      console.error('登录错误:', error)
      
      // 处理账户锁定的情况
      if (error.response?.status === 423) {
        return {
          success: false,
          message: error.response?.data?.message || '账户已被锁定，请稍后重试',
          isLocked: true
        }
      }
      
      return { 
        success: false, 
        message: error.response?.data?.message || '登录失败，请检查网络连接' 
      }
    } finally {
      loading.value = false
    }
  }

  // 退出登录
  const logout = () => {
    token.value = ''
    user.value = null
    userPermissions.value = []
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    localStorage.removeItem('userPermissions')
    delete api.defaults.headers.common['Authorization']
    
    // 触发用户登录状态变化事件
    window.dispatchEvent(new CustomEvent('userLoginStatusChanged'))
  }

  // 检查token有效性
  const checkAuth = async () => {
    if (!token.value) return false
    
    try {
      // 设置请求头
      api.defaults.headers.common['Authorization'] = `Bearer ${token.value}`
      
      // 使用轻量级接口验证token
      const response = await api.post('/api/Auth/validate-token', {})
      return response.status === 200
    } catch (error) {
      if (error.response?.status === 401) {
        logout()
        return false
      }
      return true // 其他错误不清除登录状态
    }
  }

  // 初始化时检查认证状态
  const initAuth = async () => {
    // 只在有token且不在登录页面时才验证
    if (token.value && window.location.pathname !== '/refundtask/login') {
      const isValid = await checkAuth()
      if (!isValid) {
        logout()
      }
    }
  }

  // 企业微信登录
  const weChatWorkLogin = async (code) => {
    loading.value = true
    try {
      console.log('发送企业微信登录请求:', { code })
      const response = await api.post('/api/WeChatWork/login', { code })
      
      if (response.status === 200 && response.data) {
        const { token: authToken, userInfo } = response.data
        
        // 保存到状态
        token.value = authToken
        user.value = {
          id: userInfo.userId,
          username: userInfo.userId,
          fullName: userInfo.name,
          role: 'WeChatWorkUser',
          userPhone: userInfo.mobile || '',
          avatar: userInfo.avatar || '',
          department: userInfo.department || '',
          position: userInfo.position || ''
        }
        
        // 保存到本地存储
        localStorage.setItem('token', authToken)
        localStorage.setItem('user', JSON.stringify(user.value))
        
        // 设置API默认请求头
        api.defaults.headers.common['Authorization'] = `Bearer ${authToken}`
        
        console.log('企业微信登录成功:', {
          token: authToken,
          user: user.value
        })
        
        // 获取用户权限
        try {
          const permissionResult = await getUserPermissions(user.value.username)
          if (permissionResult.success) {
            console.log('企业微信用户权限获取成功，权限数量:', permissionResult.data.length)
          } else {
            console.warn('企业微信用户权限获取失败:', permissionResult.message)
          }
        } catch (permissionError) {
          console.error('获取企业微信用户权限时发生错误:', permissionError)
        }
        
        // 触发用户登录状态变化事件
        window.dispatchEvent(new CustomEvent('userLoginStatusChanged'))
        
        return { success: true, data: response.data }
      } else {
        return { success: false, message: response.data?.message || '企业微信登录失败' }
      }
    } catch (error) {
      console.error('企业微信登录错误:', error)
      return { 
        success: false, 
        message: error.response?.data?.message || '企业微信登录失败，请重试' 
      }
    } finally {
      loading.value = false
    }
  }

  // 设置企业微信Token（用于成功页面）
  const setWeChatWorkToken = async (authToken, userInfo) => {
    try {
      token.value = authToken
      
      if (userInfo) {
        user.value = {
          id: userInfo.id || userInfo.userId,
          username: userInfo.username || userInfo.userId,
          fullName: userInfo.fullName || userInfo.name,
          role: 'WeChatWorkUser',
          userPhone: userInfo.userPhone || userInfo.mobile || '',
          avatar: userInfo.avatar || '',
          department: userInfo.department || '',
          position: userInfo.position || ''
        }
      }
      
      // 保存到本地存储
      localStorage.setItem('token', authToken)
      if (user.value) {
        localStorage.setItem('user', JSON.stringify(user.value))
      }
      
      // 设置API默认请求头
      api.defaults.headers.common['Authorization'] = `Bearer ${authToken}`
      
      // 获取用户权限
      if (user.value && user.value.username) {
        try {
          const permissionResult = await getUserPermissions(user.value.username)
          if (permissionResult.success) {
            console.log('企业微信Token设置后权限获取成功，权限数量:', permissionResult.data.length)
          } else {
            console.warn('企业微信Token设置后权限获取失败:', permissionResult.message)
          }
        } catch (permissionError) {
          console.error('企业微信Token设置后获取用户权限时发生错误:', permissionError)
        }
      }
      
      // 触发用户登录状态变化事件
      window.dispatchEvent(new CustomEvent('userLoginStatusChanged'))
      
      return true
    } catch (error) {
      console.error('设置企业微信Token失败:', error)
      return false
    }
  }

  // 获取用户权限
  const getUserPermissions = async (username) => {
    try {
      console.log('获取用户权限:', username)
      const response = await api.post('/api/UserPermission/GetUserPermissions', {
        username: username
      })
      ///api/UserPermission/GetUserPermissions
      if (response.data.success) {
        const permissions = response.data.data || []
        userPermissions.value = permissions
        localStorage.setItem('userPermissions', JSON.stringify(permissions))
        console.log('用户权限获取成功:', permissions)
        return { success: true, data: permissions }
      } else {
        console.log('用户权限获取失败:', response.data.message)
        userPermissions.value = []
        localStorage.setItem('userPermissions', JSON.stringify([]))
        return { success: false, message: response.data.message }
      }
    } catch (error) {
      console.error('获取用户权限失败:', error)
      userPermissions.value = []
      localStorage.setItem('userPermissions', JSON.stringify([]))
      return { 
        success: false, 
        message: error.response?.data?.message || '获取用户权限失败' 
      }
    }
  }

  // 保存用户权限到localStorage
  const saveUserPermissions = (permissions) => {
    userPermissions.value = permissions || []
    localStorage.setItem('userPermissions', JSON.stringify(userPermissions.value))
    console.log('用户权限已保存到localStorage:', userPermissions.value)
  }

  // 获取当前用户权限
  const getCurrentUserPermissions = () => {
    return userPermissions.value
  }

  // 检查用户是否有特定科室权限
  const hasPermissionForDepartment = (departmentCode) => {
    return userPermissions.value.some(permission => 
      permission.roleOfContextValue === departmentCode
    )
  }

  // 获取用户所有科室权限
  const getUserDepartments = () => {
    return userPermissions.value.map(permission => ({
      code: permission.roleOfContextValue,
      name: permission.name,
      roleName: permission.roleName
    }))
  }

  return {
    token,
    user,
    userPermissions,
    loading,
    isAuthenticated,
    getCaptcha,
    login,
    logout,
    checkAuth,
    initAuth,
    weChatWorkLogin,
    setWeChatWorkToken,
    getUserPermissions,
    saveUserPermissions,
    getCurrentUserPermissions,
    hasPermissionForDepartment,
    getUserDepartments
  }
})